package com.xbai.security.filter;

import com.xbai.security.security.TokenManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xbai
 * @Date 2021/4/26
 */
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {

    private RedisTemplate redisTemplate;

    private TokenManager tokenManager;

    public TokenAuthenticationFilter(AuthenticationManager authenticationManager, RedisTemplate redisTemplate, TokenManager tokenManager) {
        super(authenticationManager);
        this.redisTemplate = redisTemplate;
        this.tokenManager = tokenManager;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 获取当前认证成功用户权限信息
        UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(request);
        // 判断如果有权限信息，放到权限上下文
        if (authenticationToken != null) {
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // 从 header 获取token
        String token = request.getHeader("token");
        if (token != null) {
            // 从 token 获取用户名
            String username = tokenManager.getUserInfoFromToken(token);
            // 从 redis 获取对应权限列表
            List<String> permissionValueList = (List<String>) redisTemplate.opsForValue().get(username);
            if (permissionValueList != null) {
                Collection<SimpleGrantedAuthority> authorities = permissionValueList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
                return new UsernamePasswordAuthenticationToken(username, token, authorities);
            }
            return null;
        }
        return null;
    }
}
